package com.ixuestar.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;

public class ApiInterceptor extends HandlerInterceptorAdapter {
	
	@SuppressWarnings("unused")
	private final Logger logger = Logger.getLogger(ApiInterceptor.class);
	

    JwtUtil jwtUtil = new JwtUtil();
	
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        
//        logger.info("----------------ApiInterceptor preHandle-------------------------");
//        
//        ResponseData responseData = ResponseData.ok();  
//        String url= request.getRequestURI();
//        logger.info("----------------url:"+url);
//
//        if(url.contains("/API/") && 
//        		!(url.contains("login") || url.contains("refreshToken") || url.contains("showRandCode")
//        				 )){
//        				 
//        	String token = request.getHeader("accessToken");
//	        String tokenStr = request.getParameter("accessToken");
//	        if(token==null && tokenStr==null){
//	        	responseData = ResponseData.customerError(ErrorCode.NO_ACCESS_TOKEN.getErrorIdx(),"无token，访问被拒！");
//	        	responseMessage(response, responseData);
//	        	return false;
//	        }
//	        
//	        if(tokenStr!=null){
//	            token=tokenStr;
//	        }
//	        
//	        //如果token已经过期,
//	        if(jwtUtil.isExpired(token) && null != SessionUtils.userMap.get(token)){
//	        	responseData = ResponseData.customerError(ErrorCode.ACCESS_TOKEN_EXPIRED.getErrorIdx(),"access token过期，请重新登录或者刷新！");
//	        	responseMessage(response, responseData);
//	        	return false;
//	        }//或者在userMap缓存中不存在，则该token无效，需要重新登录
//	        else if(null == SessionUtils.userMap.get(token)){
//	        	responseData = ResponseData.customerError(ErrorCode.REFRESH_TOKEN_EXPIRED.getErrorIdx(),"无效token，请重新登录！");
//	        	responseMessage(response, responseData);
//	        	return false;
//	        }
//	        	
//	        
//	        //token=jwtUtil.updateAccessToken(token);
//	        //response.setHeader("accessToken",token);
//	        
//	        try {
//	        	//request.setAttribute("user",jwtUtil.verifyToken(token));
//	        	request.setAttribute("user", SessionUtils.userMap.get(token));
//	            //request.setAttribute("user",jwtUtil.verifyToken(token));
//	        }catch(Exception e) {
//	            this.setErrorResponse(response,e.getMessage());
//	            return  false;
//	        }
//        }
//        
//        return true;
//    }
    
    protected void setErrorResponse(HttpServletResponse response,String message) throws IOException {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(message);
        response.getWriter().flush();
        response.getWriter().close();
    }
    
    //请求不通过，返回错误信息给客户端
    @SuppressWarnings("unused")
	private void responseMessage(HttpServletResponse response, ResponseData responseData) {
    	try{
    		PrintWriter out = response.getWriter();
    		response.setContentType("application/json; charset=utf-8");  
            String json = JSONObject.toJSONString(responseData);
            out.print(json);
            out.flush();
            out.close();
    	}
    	catch(Exception e){
    		e.printStackTrace();
    	}    	
    }
}